package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.data.ResponseStausEnum;
import com.dongdongshop.service.GoodService;
import com.dongdongshop.service.GoodsDescService;
import com.dongdongshop.service.ItemCatService;
import com.dongdongshop.service.TempLateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description
 * @ClassName UploadController
 * @Author RC
 * @date 2020.12.16 16:54
 */
@Controller
@RequestMapping("oss")
public class UploadController {
    @Reference(timeout = 1000000,check = false)
    private GoodService goodService;
    @Reference(timeout = 100000,check = false)
    private ItemCatService itemCatService;
    @Reference(timeout = 100000,check = false)
    private TempLateService tempLateService;
    @Reference(timeout = 1000000,check = false)
    private GoodsDescService goodsDescService;

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @RequestMapping("upload")
    @ResponseBody
    public DataResult upload (@RequestParam("myFile") MultipartFile myFile){
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String domain = "oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI4GFsaqQb4uLC9GZsC4mJ";
        String accessKeySecret = "S1ZQKDF2FWVx4kY3dOWXA6cx1MdXuq";
        String bucketName = "firstcontent";
        // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        String objectName = "dongdongshop"+myFile.getOriginalFilename();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            logger.info("进入上传图片方法");

        // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。

            PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, myFile.getInputStream());
            String url = "https://"+ bucketName +"."+domain + "/"+objectName;
            return DataResult.response(ResponseStausEnum.SUSSCESS).setData(url);
        }catch (Exception e){
            logger.info("查询失败",e);
            return DataResult.response(ResponseStausEnum.INTERNAL_SERVER_ERROR);
        }finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

    }
}
